<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="工单编号" prop="taskCode">
        <el-input
          v-model="queryParams.taskCode"
          placeholder="请输入工单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工单状态" prop="taskStatus">
        <el-select
          v-model="queryParams.taskStatus"
          placeholder="请选择工单状态"
          clearable
        >
          <el-option
            v-for="dict in task_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:task:add']"
          >新增</el-button
        >
        <el-button type="primary" plain @click="openTaskConfig"
          >工单配置</el-button
        >
      </el-col>
      <right-toolbar
        v-model="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="taskList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="序号"
        type="index"
        width="50"
        align="center"
        prop="taskId"
      />
      <el-table-column label="工单编号" align="center" prop="taskCode" />
      <el-table-column label="设备编号" align="center" prop="innerCode" />
      <el-table-column
        label="工单类型"
        align="center"
        prop="taskType.typeName"
      />
      <el-table-column label="工单方式" align="center" prop="createType">
        <template #default="scope">
          <dict-tag :options="task_create_type" :value="scope.row.createType" />
        </template>
      </el-table-column>
      <el-table-column label="工单状态" align="center" prop="taskStatus">
        <template #default="scope">
          <dict-tag :options="task_status" :value="scope.row.taskStatus" />
        </template>
      </el-table-column>
      <el-table-column label="运营人员" align="center" prop="userName" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}')
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openTaskDetailDialog(scope.row)"
            v-hasPermi="['manage:task:edit']"
            >查看详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      page.sync="queryParams.pageNum"
      limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加工单对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="taskRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="设备编号" prop="innerCode">
          <el-input
            v-model="form.innerCode"
            placeholder="请输入设备编号"
            @blur="handleCode"
          />
        </el-form-item>
        <el-form-item label="工单类型" prop="productTypeId">
          <el-select
            v-model="form.productTypeId"
            placeholder="请选择工单类型"
            clearable
          >
            <el-option
              v-for="dict in taskTypeList"
              :key="dict.typeId"
              :label="dict.typeName"
              :value="dict.typeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="补货数量：" prop="details">
          <el-button type="text" @click="channelDetails">
            <el-icon> <List /> </el-icon>补货清单
          </el-button>
        </el-form-item>
        <el-form-item label="运营人员：" prop="userId">
          <el-select
            v-model="form.userId"
            placeholder="请选择"
            :filterable="true"
          >
            <el-option
              v-for="(item, index) in userList"
              :key="index"
              :label="item.userName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="desc">
          <el-input
            type="textarea"
            v-model="form.desc"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看详情组件 -->
    <!-- <DetailDialog
      :detailVisible="detailVisible"
      :taskId="taskId"
      :taskDada="form"
      :detailData="detailData"
      @getList="getList"
      @handleClose="handleClose"
      @handleAdd="handleAdd"
    ></DetailDialog> -->
    <!-- end -->
    <!-- 补货详情 -->
    <!-- <ReplenishmentDialog
      :channelVisible="channelVisible"
      :innerCode="form.innerCode"
      @getDetailList="getDetailList"
      @handleClose="channelDetailsClose"
    ></ReplenishmentDialog> -->
    <!-- end -->
    <!-- 工单配置 -->
    <!-- <TaskConfig
      :taskConfigVisible="taskConfigVisible"
      @handleClose="handleConfigClose"
    ></TaskConfig> -->
    <!-- end -->
  </div>
</template>


<script>
import {
  listTask,
  getTask,
  delTask,
  addTask,
  updateTask,
  getBusinessList,
  getTaskDetails,
} from '@/api/manager/task';
import { listTaskType } from '@/api/manager/taskType';
import { loadAllParams } from '@/api/page';

// 组件
import DetailDialog from './components/business-detail-dialog.vue'; //详情组件
import ReplenishmentDialog from './components/business-replenishment-dialog.vue'; //补货组件
import TaskConfig from './components/task-config.vue';

export default {
  name: 'Task',
  components: {
    DetailDialog,
    ReplenishmentDialog,
    TaskConfig
  },
  data() {
    return {
      task_status: [], // 字典 - 工单状态
      task_create_type: [], // 字典 - 工单方式
      taskList: [],
      open: false,
      loading: true,
      showSearch: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: '',
      detailVisible: false, // 查看详情弹层
      taskId: null,
      userList: [], // 运营人员列表
      channelVisible: false, // 补货弹层
      detailData: [], // 货道列表
      taskConfigVisible: false, // 工单配置弹层
      form: {
        taskId: null,
        taskCode: null,
        taskStatus: null,
        createType: null,
        innerCode: null,
        userId: null,
        userName: null,
        regionId: null,
        desc: null,
        productTypeId: null,
        addr: null,
        createTime: null,
        updateTime: null,
        details: []
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskCode: null,
        taskStatus: null,
        createType: null,
        innerCode: null,
        userName: null,
        regionId: null,
        desc: null,
        productTypeId: null,
        userId: null,
        addr: null,
        params: { isRepair: false }
      },
      rules: {
        innerCode: [
          { required: true, message: '设备编号不能为空', trigger: 'blur' }
        ],
        productTypeId: [
          { required: true, message: '设备类型不能为空', trigger: 'blur' }
        ],
        userId: [{ required: true, message: '人员不能为空', trigger: 'blur' }],
        desc: [{ required: true, message: '备注不能为空', trigger: 'blur' }]
      },
      taskTypeList: []
    };
  },
  created() {
    this.getDicts('task_status', 'task_create_type').then(res => {
      this.task_status = res[0];
      this.task_create_type = res[1];
    });
    this.getList();
    this.getTaskTypeList();
  },
  methods: {
    /** 查询运营工单列表 */
    getList() {
      this.loading = true;
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        taskId: null,
        taskCode: null,
        taskStatus: null,
        createType: null,
        innerCode: null,
        userId: null,
        userName: null,
        regionId: null,
        desc: null,
        productTypeId: null,
        addr: null,
        createTime: null,
        updateTime: null,
        details: []
      };
      this.$refs['taskRef'].resetFields();
    },

    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.$refs['queryRef'].resetFields();
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.taskId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    // 新增按钮操作
    handleAdd(val) {
      if (val === 'anew') {
        this.taskInfo();
        this.getUserList();
      } else {
        this.taskId = '';
      }
      this.reset();
      this.open = true;
      this.title = '添加运营工单';
    },

    // 提交按钮
    submitForm() {
      this.$refs['taskRef'].validate(valid => {
        if (valid) {
          const data = { ...this.form };
          data.createType = 1;
          addTask(data).then(() => {
            this.$message.success('新增成功');
            this.open = false;
            this.getList();
          });
        }
      });
    },

    // 删除按钮操作
    handleDelete(row) {
      const _taskIds = row.taskId || this.ids;
      this.$confirm('是否确认删除该数据项？')
        .then(() => delTask(_taskIds))
        .then(() => {
          this.getList();
          this.$message.success('删除成功');
        })
        .catch(() => {});
    },

    // 导出按钮操作
    handleExport() {
      this.download('manage/task/export', this.queryParams, `task_${new Date().getTime()}.xlsx`);
    },

    // 获取工单类型列表
    getTaskTypeList() {
      const page = {
        ...loadAllParams,
        type: 2
      };
      listTaskType(page).then(response => {
        this.taskTypeList = response.rows;
      });
    },

    // 填写设备编号后获取运营人员
    handleCode() {
      if (this.form.innerCode) {
        this.getUserList();
      }
    },

    // 获取运营人员列表
    getUserList() {
      getBusinessList(this.form.innerCode).then(response => {
        this.userList = response.data;
      });
    },

    // 获取工单详情
    taskInfo() {
      let dataArr = [];
      getTask(this.taskId).then(response => {
        this.form = response.data;
      });

      getTaskDetails(this.taskId).then(res => {
        this.detailData = res.data;
        dataArr = this.detailData.map(taskDetail => ({
          channelCode: taskDetail.channelCode,
          expectCapacity: taskDetail.expectCapacity,
          skuId: taskDetail.skuId,
          skuName: taskDetail.skuName,
          skuImage: taskDetail.skuImage
        }));
        this.form.details = dataArr;
      });
    },

    // 打开详情弹窗
    openTaskDetailDialog(row) {
      this.taskId = row.taskId;
      this.taskInfo();
      this.detailVisible = true;
    },

    // 关闭详情弹窗
    handleClose() {
      this.detailVisible = false;
    },

    // 打开补货清单
    channelDetails() {
      this.$refs['taskRef'].validateField('innerCode', error => {
        if (!error) return;
        this.channelVisible = true;
      });
    },

    // 关闭补货清单
    channelDetailsClose() {
      this.channelVisible = false;
    },

    // 获取货道清单数据
    getDetailList(val) {
      this.form.details = val;
    },

    // 打开工单配置弹层
    openTaskConfig() {
      this.taskConfigVisible = true;
    },

    // 关闭工单配置弹层
    handleConfigClose() {
      this.taskConfigVisible = false;
    }
  }
};
</script>
<style lang="scss" scoped src="./index.scss"></style>
